package com.wolfking.service.ssoauth.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wolfking.back.core.bean.User;

import net.sf.ehcache.Element;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

/**
 * token缓存的服务
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月23日 下午4:20:51
 * @copyright wolfking
 */
@Service
public class CacheService {
	@Autowired
	private CacheManager cacheManager;
	@Autowired
	private UserService userService;

	/**
	 * 保存tokenID和userId到缓存
	 * 
	 * @param user
	 */
	public void saveToken(User user) {
		Cache cache = cacheManager.getCache("tokenCache");
		Element element = new Element(user.getTokenId(), user.getId());
		cache.put(element);
		cache.flush();

		Cache cacheU = cacheManager.getCache("userCache");
		Element elementU = new Element(user.getId(), user.getTokenId());
		cacheU.put(elementU);
		cacheU.flush();
	}

	/**
	 * 从缓存获取登录的数据
	 * 
	 * @param user
	 */
	public User getTokenUser(String tokenId) {
		Cache cache = cacheManager.getCache("tokenCache");
		Element element = cache.get(tokenId);
		if (element == null)
			return null;
		User user = userService.getById(String.valueOf(element.getObjectValue()));
		user.setTokenId(tokenId);
		return user;
	}

	public void clearToken(String tokenId) {
		Cache cache = cacheManager.getCache("tokenCache");
		Cache cacheU = cacheManager.getCache("userCache");
		Element element = cache.get(tokenId);
		if (element != null) {
			String userId = element.getObjectValue().toString();
			cache.remove(tokenId);
			cacheU.remove(userId);
		}
	}
}
